package cake.web.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cake.dao.AddressDao;
import cake.dao.CakeOrderDao;
import cake.dao.impl.AddressDaoImpl;
import cake.dao.impl.CakeOrderDaoImpl;
import cake.entity.Address;
import cake.entity.CakeOrder;
import cake.entity.User;

@WebServlet("/user.html")
public class UserServlet extends HttpServlet{

	AddressDao addressDao = new AddressDaoImpl();
	
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		User user = (User)req.getSession().getAttribute("LoginUser");
		if(user!=null) {
			req.setAttribute("user",user);
			CakeOrderDao cakeOrderDao = new CakeOrderDaoImpl();
			List<CakeOrder> cakeOrder = cakeOrderDao.findOrderListByUid(user.getId());
			req.setAttribute("cakeOrder", cakeOrder);
			
			String did = req.getParameter("did");
			if(did!=null && did!="") {
				int id = Integer.parseInt(did);
				addressDao.deleteAddressByid(id);
			}
			List<Address> address = addressDao.getAddressByUid(user.getId());
			req.setAttribute("address",address);
			req.getRequestDispatcher("user.jsp").forward(req, resp);
			
		}else {
			resp.sendRedirect("login.jsp");
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");
		User user = (User)req.getSession().getAttribute("LoginUser");
		String address = req.getParameter("address");
		String phone = req.getParameter("phone");
		String consignee = req.getParameter("consignee");
		Address a = new Address(0,user.getId(),address,phone,consignee);
		String mid = req.getParameter("mid");
		if(mid!=null && mid!="") {
			int id = Integer.parseInt(mid);
			addressDao.updateAddress(a, id);
		}else {
			addressDao.addAddress(a);
		}
		resp.sendRedirect("user.html");
	}
		
	
	
}
